package top.goldenyear.porpoise.framework.web.core.filter;

import top.goldenyear.porpoise.framework.common.constant.PorpoiseHeader;
import top.goldenyear.porpoise.framework.isolate.core.util.TenantContext;
import top.goldenyear.porpoise.framework.web.core.util.AppContextHolder;
import cn.hutool.v7.core.convert.ConvertUtil;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;

/**
 * @author airhead
 */
public class PorpoiseWebFilter implements Filter {
  @Override
  public void doFilter(Context ctx, FilterChain chain) throws Throwable {
    try {
      String appId = ctx.header(PorpoiseHeader.PORPOISE_APPID);
      AppContextHolder.setAppId(appId);

      String tenantId = ctx.header(PorpoiseHeader.PORPOISE_TENANT_ID);
      TenantContext.enableTenant(ConvertUtil.toLong(tenantId));
      chain.doFilter(ctx);
    } finally {
      AppContextHolder.clear();
      TenantContext.clear();
    }
  }
}
